<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-row :gutter="20">
                <el-col :span="12" :offset="0">用户管理</el-col>
                <el-col :span="12" class="text-right">
                    <el-button type="primary" @click="handleAdd">添加用户</el-button>
                </el-col>
            </el-row>
        </template>
        <!-- card body -->
        <div>
            <el-form inline>
                <el-form-item>
                    <el-input v-model="searchQuery" placeholder="搜索用户名" clearable @change="handleSearch"></el-input>
                </el-form-item>                   
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="userList" v-loading="loading" style="width: 100%">
                <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
                <el-table-column label="用户名" prop="username" min-width="120"></el-table-column>
                <el-table-column label="邮箱" prop="email" min-width="200"></el-table-column>
                <el-table-column label="密码" prop="password" width="120">
                    <template #default="scope">
                        <span>********</span>
                    </template>
                </el-table-column>
                <el-table-column label="发帖数" prop="post_count" width="100"></el-table-column>
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                background
                layout="total, prev, pager, next"
                :total="total"
                :page-size="20"
                :current-page="currentPage"
                @current-change="handlePageChange"
                class="mt-4"
            ></el-pagination>
            <div class="pagination-container" style="margin-top: 20px;">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="total"
                    :page-size="20"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>



            <!-- 添加/编辑用户对话框 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
                <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="userForm.password" type="password" :placeholder="editMode ? '不修改请留空' : '请输入密码'"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitForm">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsers, addUser, updateUser, deleteUser } from '@/api/user'

// 添加表单引用
const userFormRef = ref(null)

// 数据
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editMode = ref(false)
const userForm = reactive({
    id: null,
    username: '',
    email: '',
    password: ''
})

// 表单验证规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    password: [
        { required: !editMode.value, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ]
}

// 获取用户列表
const fetchUsers = async () => {
    loading.value = true
    try {
        const res = await getUsers(searchQuery.value, currentPage.value)
        // console.log("res", res);
        
        if (res.data.code === 200) {  // 修改这里，移除 .data
            userList.value = res.data.data  // 直接使用 res.data
            total.value = res.data.total
        } else {
            ElMessage.error(res.message || '获取用户列表失败')
        }
    } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchUsers()
}

// 重置搜索
const resetSearch = () => {
    searchQuery.value = ''
    currentPage.value = 1
    fetchUsers()
}

// 页码改变
const handlePageChange = (page) => {
    currentPage.value = page
    fetchUsers()
}

// 添加用户
const handleAdd = () => {
    editMode.value = false
    dialogTitle.value = '添加用户'
    userForm.id = null
    userForm.username = ''
    userForm.email = ''
    userForm.password = ''
    dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
    editMode.value = true
    dialogTitle.value = '编辑用户'
    userForm.id = row.id
    userForm.username = row.username
    userForm.email = row.email
    userForm.password = ''
    dialogVisible.value = true
}
// 修改删除处理部分
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteUser(row.id)
            if (res.data.code === 200) {  // 正确访问响应数据
                ElMessage.success('删除成功')
                fetchUsers()
            } else {
                ElMessage.error(res.data.message || '删除失败')  // 获取后端返回的错误信息
            }
        } catch (error) {
            console.error('删除失败:', error)
            // 处理网络错误
            if (error.response) {
                ElMessage.error(`服务器错误: ${error.response.data.message}`)
            } else {
                ElMessage.error('网络连接异常')
            }
        }
    })
}

// 提交表单
const submitForm = async () => {
    if (!userFormRef.value) return
    
    userFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                if (editMode.value) {
                    const res = await updateUser(userForm.id, userForm)
                    if (res.code === 200) {
                        ElMessage.success('更新成功')
                        dialogVisible.value = false
                        fetchUsers()
                    } else {
                        ElMessage.error(res.message || '更新失败')
                    }
                } else {
                    const res = await addUser(userForm)
                    if (res.code === 200) {
                        ElMessage.success('添加成功')
                        dialogVisible.value = false
                        fetchUsers()
                    } else {
                        ElMessage.error(res.message || '添加失败')
                    }
                }
            } catch (error) {
                console.error(editMode.value ? '更新失败:' : '添加失败:', error)
                ElMessage.error(editMode.value ? '更新失败' : '添加失败')
            }
        }
    })
}

// 页面加载时获取用户列表
onMounted(() => {
    fetchUsers()
})
</script>

<style scoped>
.text-right {
    text-align: right;
}

.mt-4 {
    margin-top: 1rem;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>